package com.ideal.gpt.app.docqajob.topicjob;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.alibaba.fastjson.JSONObject;
import com.lzwork.gpt.utility.common.Passage;
import com.lzwork.utility.file.LineContent;
import com.lzwork.utility.pair.StringPair;
import com.lzwork.utility.str.StrUtility;

/**
 * @author LiZheng
 * @date 2023年11月9日 下午3:38:19
 */

public class ElementPick
{
	public static List<Block> pickItems(String str)
	{
		JSONObject obj = Passage.toJObj(str);

		List<Block> spList = extractObject(null, "", obj);

		Iterator<Block> it = spList.iterator();

		while (it.hasNext())
		{
			Block block = it.next();
			if (block.isEmpty())
				it.remove();
		}

		return spList;
	}

	public static class Block extends ArrayList<StringPair>
	{
		private static final long serialVersionUID = 1L;
	}

	protected static List<Block> extractObject(Block owner, String key, Object target)
	{
		List<Block> result = new ArrayList<>();

		if (owner == null)
		{
			owner = new Block();
			result.add(owner);
		}

		if (target instanceof Map<?, ?>)
		{
			Block block = new Block();
			result.add(block);

			Map<?, ?> map = (Map<?, ?>) target;

			for (Entry<?, ?> e : map.entrySet())
			{
				String mKey = e.getKey().toString();
				Object o = e.getValue();

				result.addAll(extractObject(block, mKey, o));
			}
		} else if (target instanceof List)
		{
			List<?> list = (List<?>) target;
			for (Object o : list)
			{
				result.addAll(extractObject(owner, key, o));
			}
		} else
		{
			owner.add(new StringPair(key, target.toString()));
		}

		return result;
	}

	public static void main(String[] args)
	{
		File file = new File("V:/12345/exam/phone.txt");

		String str = LineContent.loadString(file);
		List<Block> spList = pickItems(str);

		System.out.println(StrUtility.combineString(spList, "\n"));
	}
}
